<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DAO\EmployeeDAO;
use App\Employee;

class EmployeeController extends Controller
{
    public function __construct()
    {
        $this->middleware("auth:api");
    }

    public function getAll(){
        return response()->json(EmployeeDAO::getAll(),200);
    }

    public function getPageData(Request $req){
        $s = $req->s? trim($req->s) : '';
        $count_per_page = ($req->count_per_page+0)>0? ($req->count_per_page+0) : 5;
        $order_by = $req->order_by? trim($req->order_by) : 'id';
        $order = $req->order=='desc'? 'desc' : 'asc';
        if($order_by=='id'){
            $order_raw = "id $order";
        }
        else if($order_by=='department.name'){
            $order_raw = "department_id $order";
        }
        else{
            $order_raw = "convert($order_by using gbk) $order";
        }
        $result = Employee::with('department:id,name')->where('name','like',"%$s%")->orWhere('mobile_phone','like',"%$s%")->orWhere('work_phone','like',"%$s%")->orderByRaw($order_raw)->paginate($count_per_page);
        return response()->json($result,200);
    }


    public function getPositions(Request $req){
        $positions = [];
        $result = Employee::select('position')->distinct()->orderByRaw("convert(position using gbk)")->get();
        foreach($result as $r){
            $positions[] = $r->position;
        }
        return response()->json($positions,200);
    }

    public function getTitles(Request $req){
        $titles = [];
        $result = Employee::select('title')->distinct()->orderByRaw("convert(title using gbk)")->get();
        foreach($result as $r){
            $titles[] = $r->title;
        }
        return response()->json($titles,200);
    }
}
